package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
	
	public String paymentInfo_OK(Integer id){
		return "ThreadName:" + Thread.currentThread().getName() + " id:" + id + " Method:paymentInfo_OK";
	}
	
	@HystrixCommand(fallbackMethod = "paymentInfo_timeout_handler",commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
	})
	public String paymentInfo_timeout(Integer id){
		Integer sleeptime = 13;
		try {
			TimeUnit.SECONDS.sleep(sleeptime);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "ThreadName:" + Thread.currentThread().getName() + " id:" + id + " Method:paymentInfo_timeout";
	}
	
	
	public String paymentInfo_timeout_handler(Integer id){
		return "ThreadName:" + Thread.currentThread().getName() + " id:" + id + " Method:paymentInfo_timeout_handler";
	}
	
	//=========================服务熔断======================
	@HystrixCommand(fallbackMethod = "payment_circuitBreaker_handle",commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间窗口期
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
	})
	public String payment_circuitBreaker(@PathVariable("id")Long id){
		if (id < 0){
			throw new RuntimeException("id不能是负数!!!");
		}
		String uuid = IdUtil.randomUUID();
		return Thread.currentThread().getName() + "调用成功,流水号 :" + uuid;
	}
	
	public String payment_circuitBreaker_handle(@PathVariable("id")Long id){
		return "id不能是负数,请输入正确的id,o(╥﹏╥)o~~";
	}
}
